package com.zwj.se.collection;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;


/**
 * @author 张文接
 * @version 1.0
 * @createTime 2024/8/26 09:19
 */
public class Demo1 {
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    public static void main(String[] args) {
        //初始数组
        Object[] sourceArr = getList().toArray();
        Iterator<Object> it = Arrays.stream(sourceArr).iterator();
        int i = sourceArr.length;
        while (it.hasNext()) {
            int cap = sourceArr.length;
            if (i == cap) {
                int newCap = cap + (cap >> 1) + 1;
                // overflow-conscious code
                if (newCap - MAX_ARRAY_SIZE > 0)
                    newCap = hugeCapacity(cap + 1);
                sourceArr = Arrays.copyOf(sourceArr, newCap);
            }
            sourceArr[i++] = it.next();
        }
        Object[] targetArr = (i == sourceArr.length) ? sourceArr : Arrays.copyOf(sourceArr, i);

        for (Object o : targetArr) {
            Integer integer = (Integer) o;
            System.out.println(integer);
        }

    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError
                    ("Required array size too large");
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

    private static void demo1() {
        ArrayList<Integer> list = getList();
        Object[] objects = Arrays.copyOf(list.toArray(), 2);
        for (Object object : objects) {
            System.out.println(object);
        }
    }

    private static ArrayList<Integer> getList() {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        return list;
    }
}
